package com.ming.common.beetl.config;


import com.ming.common.beetl.entity.DataSourceEntity;
import com.ming.common.beetl.entity.SQLManagerEntity;
import com.ming.common.beetl.util.SqlUtil;
import com.ming.common.generate.template.core.GenerateTemplate;
import com.ming.common.ivy.IvyDict;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@Configuration
public class SimpleDataSourceConfig {

    @Autowired
    ApplicationContext ctx;

    @Primary
    @Bean(name = "ds0")
    public DataSource datasource(Environment env) {
        DataSourceEntity ds = new DataSourceEntity();
        ds.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
        ds.setUsername(env.getProperty("spring.datasource.username"));
        ds.setPassword(env.getProperty("spring.datasource.password"));
        return SqlUtil.buildHikariDataSource(ds);
    }

    @Bean(name = "sqlManager")
    public SQLManager sqlManager(@Qualifier("ds0") DataSource dataSource){
        SQLManagerEntity entity = new SQLManagerEntity();
        entity.setDataSource(dataSource);
        entity.setDbStyle(new MySqlStyle());
        entity.setInitSql("db/init.sql");
        SQLManager sqlManager = SqlUtil.buildSQLManager(entity);
        try {
            String[] basePackages = new String[]{"com.ming","com.ivy"};
            IvyDict ivyDict = sqlManager.lambdaQuery(IvyDict.class).andEq(IvyDict::getCode,"ivy_gen_base_package").single();
            if(ivyDict != null && cn.hutool.core.util.StrUtil.isNotBlank(ivyDict.getCode())){
                basePackages = ivyDict.getValue().split(",");
            }
            GenerateTemplate.getInstance().autoGenSql(sqlManager, basePackages);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return sqlManager;
    }
}